package com.ssm.demo.service.poi.impl;

import com.ssm.demo.service.poi.IPOIService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Service
public class POIServiceImpl implements IPOIService {

    @Override
    public void export(HttpServletRequest request, HttpServletResponse response) {

        HSSFWorkbook book = new HSSFWorkbook();
        HSSFSheet sheet = book.createSheet("成绩表");
        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell = row1.createCell(0);
        cell.setCellValue("学员考试成绩一览表");
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));


        HSSFRow row2 = sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("姓名");
        row2.createCell(1).setCellValue("班级");
        row2.createCell(2).setCellValue("笔试成绩");
        row2.createCell(3).setCellValue("机试成绩");
        //在sheet里创建第三行
        HSSFRow row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("李明");
        row3.createCell(1).setCellValue("As178");
        row3.createCell(2).setCellValue(87);
        row3.createCell(3).setCellValue(78);

        HSSFRow row4 = sheet.createRow(3);
        row4.createCell(0).setCellValue("前锋");
        row4.createCell(1).setCellValue("xyz");
        row4.createCell(2).setCellValue(100);
        row4.createCell(3).setCellValue(90);

        try {
            OutputStream output = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment; filename=details.xls");
            response.setContentType("application/msexcel");
            book.write(output);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.reset();

    }
}
